package com.epam.rentcar.controller.actions;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.epam.rentcar.DAO.UserDAO;
import com.epam.rentcar.DAO.DAOFactory;
import com.epam.rentcar.model.CarRent;
import com.epam.rentcar.transferobjects.User;
import com.epam.rentcar.utils.dbconn.ConnectionFactory;


public class LoginCheckAction implements Action {

	private DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.MySQL);
	private UserDAO userDAO = daoFactory.getUserDAO(ConnectionFactory.MySQL);

	private static Logger log = Logger.getLogger(LoginCheckAction.class);

	@Override
	public String perform(HttpServletRequest request, HttpServletResponse response) throws ServletException{

		String role = "";
		String login = "";
		String password = "";
		
		User user = null;

		try {

			role = request.getParameter("role");
			login = request.getParameter("login");
			password = request.getParameter("password");

			login = new String(login.getBytes("ISO8859_1"), "UTF-8");
			password = new String(password.getBytes("ISO8859_1"), "UTF-8");

			user = userDAO.getUser(role, login, password);

			if (user != null && user.getRole() != null && user.getLogin() != null) {
				HttpSession session = request.getSession(true);
				session.setAttribute("user", user);
				session.setAttribute("carRentAppModel", new CarRent(user.getID()));
				return "/main.jsp";
			} else {
				request.setAttribute("message", "wrong login or password");
			}
		} catch (SQLException | NamingException | UnsupportedEncodingException | NullPointerException e) {
			log.error(e);
			throw new ServletException(e);
		} 
		return "/message.jsp";
	}

	public void setMySQLDAOFactory(DAOFactory mySQLDAOFactory) {
		this.daoFactory = mySQLDAOFactory;
	}

	public void setMySQLUserDAO(UserDAO mySQLUserDAO) {
		this.userDAO = mySQLUserDAO;
	}

}
